package com.elastaticsearch.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Highlight;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.Suggester;
import com.elastaticsearch.pojo.Student;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.*;

@Controller
public class StudentController {
	@Resource
	private ElasticsearchClient client;
	@GetMapping("/auto")
	String addStudent(){
		return "auto";
	}
	@GetMapping("/autocomplete")
	@ResponseBody
	String autocomplete(String prefix) throws IOException {
		List<Student> studentList=new ArrayList<>();
		Suggester suggester = Suggester.of(s -> s.suggesters("university_suggest", p -> p.prefix(prefix).completion(c -> c.field("university").size(3).skipDuplicates(true))));
		//university_suggest是自定义的自动补全查询的名称，university是查询字段，必须是complete类型
		SearchRequest searchRequest = new SearchRequest.Builder().index("student").suggest(suggester).build();
		SearchResponse<Student> search = client.search(searchRequest, Student.class);
		int size = search.suggest().get("university_suggest").get(0).completion().options().size();
		for (int i = 0; i < size; i++) {
			Student student = search.suggest().get("university_suggest").get(0).completion().options().get(i).source();
			studentList.add(student);
		}
		return new ObjectMapper().writeValueAsString(studentList);
	}
	@GetMapping("/searchHighLight")
	String searchHighLight(){
		return "searchHighLight";
	}
	@PostMapping("/searchHighLight")
	String search(String keyword, Model model) throws IOException {
		List<Student> studentList=new ArrayList<>();
		Query query = Query.of(q -> q.match(m -> m.field("name").query(keyword)));
		String[] fields={"name"};
		Highlight highlight = Highlight.of(h -> {
			for (String field : fields) {
				h.fields(field, h1 -> h1.preTags("<b><font color='red'>").postTags("</font></b>"));
			}
			return h;
		});
		SearchRequest searchRequest = new SearchRequest.Builder().index("student").query(query).highlight(highlight).build();
		SearchResponse<Student> search = client.search(searchRequest, Student.class);
		for (Hit<Student> hit : search.hits().hits()) {
			Student student = hit.source();
			String name = hit.highlight().get("name").get(0);
			student.setName(name);
			studentList.add(student);
		}
		model.addAttribute("students",studentList);
		return "students";
	}
}
